package edu.nmt.cs.cse326.team4.crap;

import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.google.android.gms.maps.model.LatLng;

public class ViewDetailsActivity extends Activity {

	private static Toilet toilet = null; // the toilet in view
	private static Comment comment = null; // the user's comment
	private static String user = null; // currently logged in user
	private boolean rated = false;
	
	SharedPreferences prefs;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_viewdetails);
		
		prefs = getSharedPreferences("crap", 0);
		
		Intent parameters = getIntent();
		Bundle extras = parameters.getExtras();
		if (extras != null){
			toilet = (Toilet) extras.get("toilet");
		}
		
		if (toilet == null){
			//error
		}
		else{
			new GetToilet().execute();
		}
		
		// get currently logged in user from prefs
		SharedPreferences prefs = getSharedPreferences("crap",0);
		user = prefs.getString("user", null);
		EditText commentText = (EditText) findViewById(R.id.commentEdit);
		Button commentBtn = (Button) findViewById(R.id.commentButton);
		if (user == null) {
			commentText.setEnabled(false);
			commentBtn.setEnabled(false);
		}		
	}

	private void addDetails() {
		//set the name and address
		String name = toilet.getName();
		if (name != null)
			((TextView) findViewById(R.id.details_nameLabel)).setText(toilet.getName());
		String address = toilet.getAddress();
		if (address != null)
			((TextView) findViewById(R.id.details_addressLabel)).setText(toilet.getAddress());
		
		//set the rating
		RatingBar rating = ((RatingBar) findViewById(R.id.details_ratingBar));
		rating.setRating(toilet.getRating());
		rating.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				rated = true;
				
			}
			
		});
		
		//set the amenities
		LinearLayout amenityLayout = (LinearLayout) findViewById(R.id.details_amenitiesLayout);
		amenityLayout.removeAllViews();
		if (toilet.getAmenities() != null) {
			for (String amenity : toilet.getAmenities()){
				LinearLayout layout = new LinearLayout((Context) this);
				layout.setOrientation(LinearLayout.HORIZONTAL);
				TextView label = new TextView((Context) this);
				if (amenity.equals("stalls") || amenity.equals("urinals"))
					label.setText(amenity);
				else
					label.setText(amenity);
				layout.addView(label);
				amenityLayout.addView(layout);
			}
		}
		
		//set the comments
		LinearLayout commentLayout = (LinearLayout) findViewById(R.id.details_reviewLayout);
		commentLayout.removeAllViews();
		if (toilet.getComments() != null) {
			for (Comment comment: toilet.getComments()){
				LinearLayout layout = new LinearLayout(this);
				layout.setOrientation(LinearLayout.HORIZONTAL);
				TextView author = new TextView(this);
				author.setText(comment.getAuthor() + ":  ");
				TextView commentView = new TextView(this);
				commentView.setGravity(Gravity.RIGHT);
				
				commentView.setText(comment.getComment());
				layout.addView(author);
				layout.addView(commentView);
				commentLayout.addView(layout);
			}
		}
	}
	
	public void sendCorrection(View view){
		Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "correction: " + toilet.getName() + ", " + toilet.getAddress());
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"m0pt0pmatt@gmail.com"});
        emailIntent.setType("plain/text");
        startActivity(Intent.createChooser(emailIntent, "Send us an email of what details are inaccurate."));
	}
	
	public void openNavigate(View view){
		LatLng latLng = toilet.getLocation();
		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" +latLng.latitude+","+latLng.longitude));
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}
	
	public void startComment(View view){
		EditText commentText = (EditText) findViewById(R.id.commentEdit);
		String text = commentText.getText().toString();
		float rating = ((RatingBar) findViewById(R.id.details_ratingBar)).getRating();
		if (!text.equals("")) {
			comment  = new Comment(user, text, new Date(), rating);
			new AddComment().execute();
			commentText.setText("");
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		if (prefs.getString("user", null) != null)
			getMenuInflater().inflate(R.menu.list_view, menu);
		else
			getMenuInflater().inflate(R.menu.unreg_list_view, menu);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings:
			Intent intent = new Intent(this, SettingsActivity.class);
			startActivity(intent);
			finish();
			return true;
		case R.id.map_view:
			intent = new Intent(this, ViewMapActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			finish();
			return true;
		case R.id.login:
			intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
			finish();
		case R.id.logout:
			prefs.edit().putString("user", null).commit();
			intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
			finish();
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Background task to get toilet details from the server.
	 * @author james
	 *
	 */
	class GetToilet extends AsyncTask<String, String, String> {

		/**
		 * Go get that toilet!
		 */
		@Override
		protected String doInBackground(String... params) {
			toilet = DBAdapter.getToilet(toilet.getId());
			return null;
		}
		
		/**
		 * After getting toilet, update details.
		 */
		protected void onPostExecute(String result) {
			addDetails();
		}
		
	}

	/**
	 * Background task to add a comment.
	 * @author james
	 *
	 */
	class AddComment extends AsyncTask<String, String, String> {

		/**
		 * Go get that toilet!
		 */
		@Override
		protected String doInBackground(String... params) {
			// add comment to db
			DBAdapter.addComment(toilet.getId(), comment);
			// refresh toilet details
			toilet = DBAdapter.getToilet(toilet.getId());
			
			
			return null;
		}
		
		/**
		 * After getting toilet, update details.
		 */
		protected void onPostExecute(String result) {
			addDetails();
		}
		
	}

}

